/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.settlement.web.investorsettlement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.lang.ObjectUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.agreement.entity.yearcarsalepurchaseagreement.YearCarSalePurchaseAgreement;
import com.jeesite.modules.agreement.service.yearcarsalepurchaseagreement.YearCarSalePurchaseAgreementService;
import com.jeesite.modules.base.entity.fixedexpense.FixedExpense;
import com.jeesite.modules.base.service.fixedexpense.FixedExpenseService;
import com.jeesite.modules.order.dao.serviceorder.ServiceOrderDetailDao;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.pay.dao.TpaymentDao;
import com.jeesite.modules.pay.dao.TpaymentDetailDao;
import com.jeesite.modules.pay.entity.Tpay;
import com.jeesite.modules.pay.entity.TpaymentDetail;
import com.jeesite.modules.prepay.dao.TprepaymentEstimatedDao;
import com.jeesite.modules.prepay.entity.TprepaymentEstimated;
import com.jeesite.modules.settlement.entity.customersettlement.CustomerSettlementDetail;
import com.jeesite.modules.settlement.entity.customersettlement.CustomerSettlementPayment;
import com.jeesite.modules.settlement.entity.investorsettlement.InvestorSettlementDetail;
import com.jeesite.modules.settlement.entity.investorsettlement.InvestorSettlementPayment;
import com.jeesite.modules.settlement.entity.investorsettlement.InvestorSettlementPrepayment;
import com.jeesite.modules.settlement.util.CopyObjectUtil;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.settlement.entity.investorsettlement.InvestorSettlement;
import com.jeesite.modules.settlement.service.investorsettlement.InvestorSettlementService;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 资方结算单Controller
 * @author Kilo
 * @version 2021-03-10
 */
@Controller
@RequestMapping(value = "${adminPath}/settlement/investorsettlement/investorSettlement")
public class InvestorSettlementController extends BaseController {

	@Autowired
	private InvestorSettlementService investorSettlementService;

	@Autowired
	private ServiceOrderService serviceOrderService;

	@Autowired
	private ServiceOrderDetailDao serviceOrderDetailDao;

	@Autowired
	private TprepaymentEstimatedDao tprepaymentEstimatedDao;

	@Autowired
	private TpaymentDetailDao tpaymentDetailDao;

	@Autowired
	private YearCarSalePurchaseAgreementService yearCarSalePurchaseAgreementService;

	@Autowired
	private FixedExpenseService fixedExpenseService;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public InvestorSettlement get(String investorSettlementId, boolean isNewRecord) {
		return investorSettlementService.get(investorSettlementId, isNewRecord);
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("settlement:investorsettlement:investorSettlement:view")
	@RequestMapping(value = {"list", ""})
	public String list(InvestorSettlement investorSettlement, Model model) {
		model.addAttribute("investorSettlement", investorSettlement);
		return "modules/settlement/investorsettlement/investorSettlementList";
	}

	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("settlement:investorsettlement:investorSettlement:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<InvestorSettlement> listData(InvestorSettlement investorSettlement, HttpServletRequest request, HttpServletResponse response) {
		investorSettlement.setPage(new Page<>(request, response));
		Page<InvestorSettlement> page = investorSettlementService.findPage(investorSettlement);
		List<InvestorSettlement> investorSettlements = page.getList();
		for(InvestorSettlement investorSettlement1:investorSettlements){
			investorSettlement1.setInvestorName(investorSettlement1.getInvestor().getSupplierName());
		}
		page.setList(investorSettlements);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("settlement:investorsettlement:investorSettlement:view")
	@RequestMapping(value = "form")
	public String form(InvestorSettlement investorSettlement, Model model) {
		if(StringUtils.isNotEmpty(investorSettlement.getInvestorSettlementId())){
			investorSettlement = investorSettlementService.get(investorSettlement.getInvestorSettlementId());
		}
		//服务订单处理
		ServiceOrder serviceOrder = serviceOrderService.get(investorSettlement.getServiceOrderId());
		investorSettlement.setServiceOrderCode(serviceOrder.getServiceOrderCode());
		//费用项目处理
		List<FixedExpense> fixedExpenseList = fixedExpenseService.findList(new FixedExpense());
		Map<String,String> map = new HashMap<>();
		for (FixedExpense fixedExpense:fixedExpenseList){
			map.put(fixedExpense.getFixedExpenseId(),fixedExpense.getFixedExpenseName());
		}
		for (InvestorSettlementPrepayment investorSettlementPrepayment:investorSettlement.getInvestorSettlementPrepaymentList()){
			investorSettlementPrepayment.setPrepaymentType(map.get(investorSettlementPrepayment.getPrepaymentType()));
		}
		for (InvestorSettlementPayment investorSettlementPayment:investorSettlement.getInvestorSettlementPaymentList()){
			investorSettlementPayment.setExpenseItem(map.get(investorSettlementPayment.getExpenseItem()));
		}
		investorSettlement.setInvestorName(investorSettlement.getInvestor().getSupplierName());
		model.addAttribute("investorSettlement", investorSettlement);
		//合计信息合计
		List<InvestorSettlementDetail> investorSettlementDetailList = investorSettlement.getInvestorSettlementDetailList();
		double payableAmountTotal = 0d;
		double actualAmountTotal = 0d;
		for(InvestorSettlementDetail investorSettlementDetail:investorSettlementDetailList){
			if(ObjectUtils.isNotEmpty(investorSettlementDetail.getPayableAmount())){
				payableAmountTotal = NumberUtils.add(payableAmountTotal,investorSettlementDetail.getPayableAmount());
			}
			if(ObjectUtils.isNotEmpty(investorSettlementDetail.getActualAmount())){
				actualAmountTotal = NumberUtils.add(actualAmountTotal,investorSettlementDetail.getActualAmount());
			}
		}
		model.addAttribute("payableAmountTotal",payableAmountTotal);
		model.addAttribute("actualAmountTotal",actualAmountTotal);

		//payment合计
		List<InvestorSettlementPayment> investorSettlementPaymentList = investorSettlement.getInvestorSettlementPaymentList();
		double actualAmountTotalPayment = 0d;
		for(InvestorSettlementPayment investorSettlementPayment:investorSettlementPaymentList){
			if(ObjectUtils.isNotEmpty(investorSettlementPayment.getActualAmount())){
				actualAmountTotalPayment = NumberUtils.add(actualAmountTotalPayment,investorSettlementPayment.getActualAmount());
			}
		}
		model.addAttribute("actualAmountTotalPayment",actualAmountTotalPayment);
		return "modules/settlement/investorsettlement/investorSettlementForm";
	}

	/**
	 * 查看表单详情
	 */
	@RequiresPermissions("settlement:investorsettlement:investorSettlement:view")
	@RequestMapping(value = "detail")
	public String detail(InvestorSettlement investorSettlement, Model model) {
		//服务订单处理
		ServiceOrder serviceOrder = serviceOrderService.get(investorSettlement.getServiceOrderId());
		investorSettlement.setServiceOrderCode(serviceOrder.getServiceOrderCode());
		//费用项目处理
		List<FixedExpense> fixedExpenseList = fixedExpenseService.findList(new FixedExpense());
		Map<String,String> map = new HashMap<>();
		for (FixedExpense fixedExpense:fixedExpenseList){
			map.put(fixedExpense.getFixedExpenseId(),fixedExpense.getFixedExpenseName());
		}
		for (InvestorSettlementPrepayment investorSettlementPrepayment:investorSettlement.getInvestorSettlementPrepaymentList()){
			investorSettlementPrepayment.setPrepaymentType(map.get(investorSettlementPrepayment.getPrepaymentType()));
		}
		for (InvestorSettlementPayment investorSettlementPayment:investorSettlement.getInvestorSettlementPaymentList()){
			investorSettlementPayment.setExpenseItem(map.get(investorSettlementPayment.getExpenseItem()));
		}
		investorSettlement.setInvestorName(investorSettlement.getInvestor().getSupplierName());
		model.addAttribute("investorSettlement", investorSettlement);
		//合计信息合计
		List<InvestorSettlementDetail> investorSettlementDetailList = investorSettlement.getInvestorSettlementDetailList();
		double payableAmountTotal = 0d;
		double actualAmountTotal = 0d;
		for(InvestorSettlementDetail investorSettlementDetail:investorSettlementDetailList){
			if(ObjectUtils.isNotEmpty(investorSettlementDetail.getPayableAmount())){
				payableAmountTotal = NumberUtils.add(payableAmountTotal,investorSettlementDetail.getPayableAmount());
			}
			if(ObjectUtils.isNotEmpty(investorSettlementDetail.getActualAmount())){
				actualAmountTotal = NumberUtils.add(actualAmountTotal,investorSettlementDetail.getActualAmount());
			}
		}
		model.addAttribute("payableAmountTotal",payableAmountTotal);
		model.addAttribute("actualAmountTotal",actualAmountTotal);

		//payment合计
		List<InvestorSettlementPayment> investorSettlementPaymentList = investorSettlement.getInvestorSettlementPaymentList();
		double actualAmountTotalPayment = 0d;
		for(InvestorSettlementPayment investorSettlementPayment:investorSettlementPaymentList){
			if(ObjectUtils.isNotEmpty(investorSettlementPayment.getActualAmount())){
				actualAmountTotalPayment = NumberUtils.add(actualAmountTotalPayment,investorSettlementPayment.getActualAmount());
			}
		}
		model.addAttribute("actualAmountTotalPayment",actualAmountTotalPayment);
		return "modules/settlement/investorsettlement/investorSettlementDetail";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("settlement:investorsettlement:investorSettlement:edit")
	@PostMapping(value = "submitSave")
	@ResponseBody
	public String submitSave(String serviceOrderId,String frameNumbersStr) {
		InvestorSettlement investorSettlement = new InvestorSettlement();
		//配置主表信息
		investorSettlement.setServiceOrderId(serviceOrderId);
		ServiceOrder serviceOrder = serviceOrderService.get(serviceOrderId);
		CopyObjectUtil.copyProperties(serviceOrder,investorSettlement,true);

		//获取年度汽车买卖协议
		YearCarSalePurchaseAgreement yearCarSalePurchaseAgreement = new YearCarSalePurchaseAgreement();
		yearCarSalePurchaseAgreement.setYearCarSalePurchaseAgreementCode(serviceOrder.getYearCarSalePurchaseAgreementId());
		List<YearCarSalePurchaseAgreement> yearCarSalePurchaseAgreements  = yearCarSalePurchaseAgreementService.findList(yearCarSalePurchaseAgreement);
		if(ObjectUtils.isEmpty(yearCarSalePurchaseAgreements)){
			return renderResult(Global.FALSE, text("年度协议未配置！"));
		}
		else {
			investorSettlement.setYearCarSalePurchaseAgreementCode(yearCarSalePurchaseAgreement.getYearCarSalePurchaseAgreementCode());
		}
		investorSettlement.setFinancialReviewFlag("0");

		//detail子表信息
		List<InvestorSettlementDetail> investorSettlementDetailList = new ArrayList<>();
		Map<String,Object> paramsMap = new HashMap<>();
		paramsMap.put("serviceOrderId",serviceOrder.getServiceOrderId());
		String[] frameNumberArr = frameNumbersStr.split(",");
		List<String> frameNumberList = Arrays.asList(frameNumberArr);
		paramsMap.put("frameNumbers",frameNumberList);
		List<Map<String,Object>> mainList = serviceOrderDetailDao.getCarJSReport(paramsMap);
		for(Map<String,Object> mainMap:mainList){
			InvestorSettlementDetail investorSettlementDetail = new InvestorSettlementDetail();
			if(ObjectUtils.isNotEmpty(mainMap.get("carId"))) {
				investorSettlementDetail.setCarId(String.valueOf(mainMap.get("carId")));
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("frameNumber"))) {
				investorSettlementDetail.setFrameNumber(String.valueOf(mainMap.get("frameNumber")));
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("amount"))) {
				investorSettlementDetail.setPrice(((BigDecimal)mainMap.get("amount")).doubleValue());
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("currency"))) {
				investorSettlementDetail.setCurrency(String.valueOf(mainMap.get("currency")));
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("tentativeExchangeRate"))) {
				investorSettlementDetail.setEstimateExchangeRate(String.valueOf(mainMap.get("tentativeExchangeRate")));
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("investorRealExchangeRate"))) {
				investorSettlementDetail.setActualExchangeRate(String.valueOf(mainMap.get("investorRealExchangeRate")));
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("pApAmount"))) {
				investorSettlementDetail.setPayableAmount(((BigDecimal)mainMap.get("pApAmount")).doubleValue());
			}
			if(ObjectUtils.isNotEmpty(mainMap.get("pActualApAmount"))) {
				investorSettlementDetail.setActualAmount(((BigDecimal)mainMap.get("pActualApAmount")).doubleValue());
			}
			investorSettlementDetailList.add(investorSettlementDetail);
		}
		investorSettlement.setInvestorSettlementDetailList(investorSettlementDetailList);

		//prepayment子表信息
		List<InvestorSettlementPrepayment> investorSettlementPrepaymentList = new ArrayList<>();
		//预付款信息列表
		List<TprepaymentEstimated> tprepaymentEstimatedList = tprepaymentEstimatedDao.findPrepaymentEstimatedInfo(frameNumberList);
		//获取预付资方余额总金额
		double paymentAmountEstimatedBalance = 0d;
		for (TprepaymentEstimated tprepaymentEstimated:tprepaymentEstimatedList){
			InvestorSettlementPrepayment investorSettlementPrepayment = new InvestorSettlementPrepayment();
			CopyObjectUtil.copyProperties(tprepaymentEstimated,investorSettlementPrepayment,true);
			if(ObjectUtils.isNotEmpty(tprepaymentEstimated.getPaymentSumActual())) {
				investorSettlementPrepayment.setAmount(tprepaymentEstimated.getPaymentSumActual());
			}
			if(ObjectUtils.isNotEmpty(tprepaymentEstimated.getPaymentAmountActual())) {
				investorSettlementPrepayment.setVerificationAmount(tprepaymentEstimated.getPaymentAmountActual());
			}
			if(ObjectUtils.isNotEmpty(tprepaymentEstimated.getPaymentAmountEstimated())) {
				investorSettlementPrepayment.setRemainingAmount(tprepaymentEstimated.getPaymentAmountEstimated());
			}
			paymentAmountEstimatedBalance = NumberUtils.add(paymentAmountEstimatedBalance,tprepaymentEstimated.getPaymentAmountEstimated());
			investorSettlementPrepaymentList.add(investorSettlementPrepayment);
		}
		investorSettlement.setPrepaymentBalance(paymentAmountEstimatedBalance);
		investorSettlement.setInvestorPrepaymentBalance(paymentAmountEstimatedBalance);
		investorSettlement.setInvestorSettlementPrepaymentList(investorSettlementPrepaymentList);

		//payment子表信息
		List<InvestorSettlementPayment> investorSettlementPaymentList = new ArrayList<>();
		//付款信息
		List<TpaymentDetail> tpayList = tpaymentDetailDao.selectPaymentDetailInfo(frameNumberList);
		for(TpaymentDetail tpaymentDetail:tpayList){
			InvestorSettlementPayment investorSettlementPayment = new InvestorSettlementPayment();
			CopyObjectUtil.copyProperties(tpaymentDetail,investorSettlementPayment,true);
			if(ObjectUtils.isNotEmpty(tpaymentDetail.getActualApAmount())) {
				investorSettlementPayment.setActualAmount(tpaymentDetail.getActualApAmount());
			}
			investorSettlementPayment.setIfFlag(tpaymentDetail.getPrepaymentCode());
			investorSettlementPaymentList.add(investorSettlementPayment);
		}
		investorSettlement.setInvestorSettlementPaymentList(investorSettlementPaymentList);
		investorSettlementService.save(investorSettlement);
		return investorSettlement.getInvestorSettlementId();
	}

	/**
	 * 操作员保存
	 */
	@RequiresPermissions("settlement:investorsettlement:investorSettlement:edit")
	@PostMapping(value = "optSave")
	@ResponseBody
	public String optSave(InvestorSettlement investorSettlement) {
		InvestorSettlement investorSettlement1 = investorSettlementService.get(investorSettlement.getInvestorSettlementId());
		investorSettlement1.setDate(investorSettlement.getDate());
		if(StringUtils.isNotEmpty(investorSettlement.getRemarks())) {
			investorSettlement1.setRemarks(investorSettlement.getRemarks());
		}
		investorSettlement1.setIsNewRecord(false);
		investorSettlementService.saveFin(investorSettlement);
		return renderResult(Global.TRUE, text("保存成功！"));
	}

	/**
	 * 财务复核
	 */
	@RequiresPermissions("settlement:investorsettlement:investorSettlement:edit")
	@PostMapping(value = "finCheckSave")
	@ResponseBody
	public String finCheckSave(InvestorSettlement investorSettlement) {
		InvestorSettlement investorSettlement1 = investorSettlementService.get(investorSettlement.getInvestorSettlementId());
		if(StringUtils.isNotEmpty(investorSettlement.getFinancialReviewMemo())) {
			investorSettlement1.setFinancialReviewMemo(investorSettlement.getFinancialReviewMemo());
		}
        investorSettlement1.setFinancialReviewFlag("1");
        investorSettlement1.setIsNewRecord(false);
        investorSettlementService.saveFin(investorSettlement);
		return renderResult(Global.TRUE, text("财务复核成功！"));
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("settlement:investorsettlement:investorSettlement:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated InvestorSettlement investorSettlement) {
		investorSettlementService.save(investorSettlement);
		return renderResult(Global.TRUE, text("保存资方结算单成功！"));
	}

	/**
	 * 删除数据
	 */
	@RequiresPermissions("settlement:investorsettlement:investorSettlement:delete")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(InvestorSettlement investorSettlement) {
		investorSettlementService.delete(investorSettlement);
		return renderResult(Global.TRUE, text("删除资方结算单成功！"));
	}

}
